package tabletask

import (
	"fmt"

	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/xuri/excelize/v2"

	"cvevulner/cve-timed-task/db_models"
)

func GenerateTable(path string) {
	ormModel := orm.NewOrm()
	results, rowsAffected, err := db_models.GetCveOriginExcel(ormModel)
	if err != nil {
		logs.Error("db_models.GetCveOriginExcel error:", err)
		return
	}
	if rowsAffected == 0 {
		logs.Info("The query result is empty, no error data")
		return
	}

	f := excelize.NewFile()
	index, _ := f.NewSheet("Sheet1")
	f.SetActiveSheet(index)

	cc := []string{"cve_id", "cve_num", "cve_url", "cve_version", "pack_name",
		"score_type", "nvd_score", "cve_level", "cve_desc", "repair_time",
		"vector_value", "attack_vector", "access_vector", "attack_complexity",
		"access_complexity", "privilege_required", "user_interaction", "scope",
		"confidentiality", "integrity", "availability", "authentication", "cve_status",
		"create_time", "update_time", "delete_time"}
	rowBegin := "A1"
	err = f.SetSheetRow("Sheet1", rowBegin, &cc)
	if err != nil {
		logs.Error("set row title error:", err)
		return
	}

	for k, v := range results {
		rowBegin = fmt.Sprintf("A%d", k+2)
		err = f.SetSheetRow("Sheet1", rowBegin, &[]interface{}{v.CveId,
			v.CveNum, v.CveUrl, v.CveVersion, v.PackName, v.ScoreType, v.NVDScore,
			v.CveLevel, v.CveDesc, v.RepairTime, v.NVDVector, v.AttackVector,
			v.AccessVector, v.AttackComplexity, v.AccessComplexity, v.PrivilegeRequired,
			v.UserInteraction, v.Scope, v.Confidentiality, v.Integrity, v.Availability,
			v.Authentication, v.CveStatus, v.CreateTime, v.UpdateTime, v.UpdateTime})
		if err != nil {
			logs.Error("f.SetSheetRow error:", err, rowBegin)
			continue
		}
	}
	err = f.SaveAs(path)
	if err != nil {
		logs.Error("f.SaveAs error: ", err, path)
	}
	err = db_models.UpdateStatusTypeTwo(ormModel)
	if err != nil {
		logs.Error("db_models.UpdateStatusTypeTwo error: ", err)
	}
}
